package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Emp;
import com.itheima.pojo.ExprList;
import com.itheima.pojo.PageBody;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Override
    public PageBody findAllByPage(String name, Integer gender, String begin, String end, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Emp> list = employeeMapper.findAllByPage(name, gender, begin, end);
        System.out.println(list);
        PageInfo<Emp> pageInfo =  new PageInfo<>(list);
        return new PageBody(pageInfo.getTotal(),pageInfo.getList().toArray());
    }

    @Override
    public void saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        Dept deptById = deptMapper.findDeptById(emp.getDeptId());
        emp.setDeptName(deptById.getName());
        System.out.println("emp====>"+emp);
        employeeMapper.saveEmp(emp);
        List<ExprList> exprList = emp.getExprList();
        Integer id = emp.getId();
        emp.setPassword("123456");
        // 批量插入exprList中的数据
        for (ExprList exprList1 : exprList) {
            exprList1.setEmpId(id);
        }
        System.out.println("exprList===>"+exprList);
        employeeMapper.saveExprList(exprList);
    }

    @Override
    public Emp findEmpById(Integer id) {
        Emp empById = employeeMapper.findEmpById(id);
        empById.setExprList(employeeMapper.findExprListByEmpId(id));
        return empById;
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        employeeMapper.deleteByIds(ids);
        employeeMapper.deleteExprListByEmpIds(ids);
    }

    @Override
    public void updateEmpById(Emp emp) {
        // 先删除此人之前的工作经历
        employeeMapper.deleteExprListByEmpId(emp.getId());
        employeeMapper.updateEmpById(emp);
        System.out.println("emp====>"+emp);
        emp.setUpdateTime(LocalDateTime.now());
        // 批量插入exprList中的数据
        List<ExprList> exprList = emp.getExprList();
        if(exprList != null&&exprList.size()!=0){
            for (ExprList exprList1 : exprList) {
                exprList1.setEmpId(emp.getId());
            }
            employeeMapper.saveExprList(exprList);
        }
    }

    @Override
    public List<Emp> findAll() {
        return employeeMapper.findAll();
    }
}
